package com.sdhs.paas.sdk.core.web.client;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

import com.sdhs.paas.sdk.core.web.PaasResponseErrorHandler;

@Configuration
public class PaasRestTemplateAutoConfiguration {
	@Bean // 定义REST客户端，RestTemplate实例
	@LoadBalanced // 开启负债均衡的能力
	@Qualifier("internalRestTemplate")
	@Primary
	public PaasRestTemplate internalRestTemplate() {
		PaasRestTemplate restTemplate = new PaasRestTemplate();
		restTemplate.setErrorHandler(paasResponseErrorHandler());
		restTemplate.getInterceptors().add(paasHttpRequestInterceptor());
		return restTemplate;
	}

	@Bean // 用来访问外部url
	@Qualifier("externalRestTemplate")
	public PaasRestTemplate externalRestTemplate() {
		PaasRestTemplate restTemplate = new PaasRestTemplate(new SimpleClientHttpRequestFactory(), "external");
		restTemplate.getInterceptors().add(paasHttpRequestInterceptor());
		restTemplate.setErrorHandler(paasResponseErrorHandler());
		return restTemplate;
	}
	
	@Bean
	@LoadBalanced
	@Qualifier("internalAsyncRestTemplate")
	@Primary
	public PaasAsyncRestTemplate paasAsyncRestTemplate() {
		SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
		taskExecutor.setConcurrencyLimit(400);
		PaasAsyncRestTemplate asyncRestTemplate = new PaasAsyncRestTemplate(taskExecutor, "internal");
//		asyncRestTemplate.setErrorHandler(paasResponseErrorHandler());
		return asyncRestTemplate;
	}

	@Bean
	@Qualifier("externalAsyncRestTemplate")
	public PaasAsyncRestTemplate externalPaasAsyncRestTemplate() {
		SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
		taskExecutor.setConcurrencyLimit(400);
		PaasAsyncRestTemplate asyncRestTemplate = new PaasAsyncRestTemplate(taskExecutor, "external");
		return asyncRestTemplate;
	}
	
	@Bean
	public PaasHttpRequestInterceptor paasHttpRequestInterceptor() {
		PaasHttpRequestInterceptor paasHttpRequestInterceptor = new PaasHttpRequestInterceptor();
		return paasHttpRequestInterceptor;
	}
	
	@Bean
	public PaasResponseErrorHandler paasResponseErrorHandler() {
		PaasResponseErrorHandler paasResponseErrorHandler = new PaasResponseErrorHandler();
		return paasResponseErrorHandler;
	}
}
